home *** CD-ROM | disk | FTP | other *** search
/ Aminet 34 / Aminet 34 (2000)(Schatztruhe)[!][Dec 1999].iso / Aminet / util / gnu / unixcmds.lha / unixcmds / src / fold.c < prev    next >
Encoding:
C/C++ Source or Header  |  1999-10-06  |  1.8 KB  |  84 lines

  1.  
  2. /* fold - folds long lines              Author: Terrence W. Holm */
  3.  
  4. /*  Usage:  fold  [ -width ]  [ file ... ]  */
  5.  
  6. #include <stdlib.h>
  7. #include <stdio.h>
  8. #include "amigawildcard.h"
  9.  
  10. #define  TAB            8
  11. #define  DEFAULT_WIDTH  80
  12.  
  13. int column = 0;                 /* Current column, retained between files  */
  14.  
  15. int main (int argc, char **argv);
  16. void Fold (FILE *f, int width);
  17.  
  18. int main(argc, argv)
  19. /* [<][>][^][v][top][bottom][index][help] */
  20. int argc;
  21. char *argv[];
  22. {
  23.   int width = DEFAULT_WIDTH;
  24.   int i;
  25.   FILE *f;
  26.   t_strlist strl;
  27.  
  28.   if (argc > 1 && argv[1][0] == '-') {
  29.         if ((width = atoi(&argv[1][1])) <= 0) {
  30.                 fprintf(stderr, "Bad number for fold\n");
  31.                 exit(1);
  32.         }
  33.         --argc;
  34.         ++argv;
  35.   }
  36.  
  37.   if (argc == 1)
  38.         Fold(stdin, width);
  39.   else {
  40.         fill_list(argv,1,argc,&strl);
  41.  
  42.         for (i = 0; i < strl.len; i++) {
  43.                 char *infile;
  44.                 infile=pop_elt(i,&strl);
  45.                 if ((f = fopen(infile, "r")) == NULL) {
  46.                         perror(infile);
  47.                         clear_list(&strl);
  48.                         exit(1);
  49.                 }
  50.                 Fold(f, width);
  51.                 fclose(f);
  52.         }
  53.   }
  54.   clear_list(&strl);
  55.   return(0);
  56. }
  57.  
  58.  
  59. void Fold(f, width)
  60. /* [<][>][^][v][top][bottom][index][help] */
  61. FILE *f;
  62. int width;
  63. {
  64.   int c;
  65.  
  66.   while ((c = getc(f)) != EOF) {
  67.         if (c == '\t')
  68.                 column = (column / TAB + 1) * TAB;
  69.         else if (c == '\b')
  70.                 column = column > 0 ? column - 1 : 0;
  71.         else if (c == '\n' || c == '\r')
  72.                 column = 0;
  73.         else
  74.                 ++column;
  75.  
  76.         if (column > width) {
  77.                 putchar('\n');
  78.                 column = c == '\t' ? TAB : 1;
  79.         }
  80.         putchar(c);
  81.   }
  82. }
  83. /* [<][>][^][v][top][bottom][index][help] */
  84.